<template>
    <div class="box">
        <div class="table-title">{{ definePropsMsg.tableTitle }}</div>
        <div class="table-action-box">
            <el-button type="primary" class="table-actionBox-addBtn" @click="roleOperate(0)">
                <span class="table-actionBox-addBtn-icon">+</span><span>新增</span>
            </el-button>
            <el-input v-model="searchInput" placeholder="请输入用户名/姓名" class="table-actionBox-searchInput">
                <template #suffix>
                    <el-icon @click="findAdmin" class="table-actionBox-searchInput-icon">
                        <search />
                    </el-icon>
                </template>
            </el-input>
        </div>
        <table class="table" v-loading="tableDataLoading">
            <tr>
                <th>角色ID</th>
                <th>用户名</th>
                <th>排序</th>
                <th>添加时间</th>
                <th>修改时间</th>
                <th>操作</th>
            </tr>
            <tr v-if="tableData.length > 0" v-for="i of tableData">
                <td>{{ i.role_id }}</td>
                <td>{{ i.role_name }}</td>
                <td>{{ i.sort }}</td>
                <td>{{ Format.timeFormat(i.created_at) }}</td>
                <td>{{ Format.timeFormat(i.updated_at) }}</td>
                <td class="edit-btn"><span @click="roleOperate(1, i)">编辑</span><span
                        @click="roleOperate(2, i)">删除</span>
                </td>
            </tr>
            <tr v-else>
                <td colspan="6" style="border-bottom: none;">
                    <el-empty description="No Data" />
                </td>
            </tr>
        </table>
        <el-pagination v-if="tableData.length > 0" class="table-pagination" :page-size="tablePagination.pageSize"
            layout="prev, pager, next" :total="tablePagination.total" v-model:current-page="currentPage" />
    </div>

    <el-dialog v-model="addBtnDialogVisible" title="新增角色" width="45%" :before-close="formHandleClose">
        <div class="dialog-box">
            <el-form ref="addRoleFormRef" :model="addRoleForm" :rules="addRoleFormRules" :label-width="100">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName" />
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-tree ref="formTreeRef" :data="permissionTreeDefault" show-checkbox node-key="id"
                        highlight-current accordion></el-tree>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="addRoleForm.sort" :min="0" controls-position="right" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="formHandleClose()">取消</el-button>
                <el-button type="primary" @click="formHandleCofirm(0)">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="editBtnDialogVisible" title="编辑管理员" width="45%" :before-close="formHandleClose">
        <div class="dialog-box">
            <el-form ref="editAdminFormRef" :model="editAdminForm" :rules="editAdminFormRules" :label-width="100">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editAdminForm.roleName" />
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-tree ref="formTreeRef" :data="permissionTreeDefault" show-checkbox node-key="id"
                        :default-checked-keys="defaultCheckedKeys" highlight-current accordion></el-tree>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="editAdminForm.sort" :min="0" controls-position="right" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="formHandleClose()">取消</el-button>
                <el-button type="primary" @click="formHandleCofirm(1)">确定</el-button>
            </span>
        </template>
    </el-dialog>

</template>
<script setup>
import { ref, getCurrentInstance, watch, reactive, nextTick } from 'vue';
import { Format } from '/util/CommonFunctions.js'
import { ElMessageBox, ElMessage } from 'element-plus';

// import { storeToRefs } from 'pinia';
// import { piniaMainStore } from '../../../store/mainStore'
const { proxy } = getCurrentInstance()
const token = window.localStorage.getItem('token')
// const pinaData = piniaMainStore() // 引入主仓库
// let { navInfo } = storeToRefs(pinaData) // 变为响应式

let definePropsMsg = defineProps(['tableTitle']) //从父组件接收到的表格标题

const roleFormMultiple = [ //下拉菜单选择项
    { id: 1, label: '超级管理员' },
    { id: 2, label: '测试角色' },
    { id: 3, label: '待定1' },
    { id: 4, label: '待定2' },
    { id: 5, label: '待定3' },
]
// ------------------------------------------------------------------------------------------新增------
let addBtnDialogVisible = ref(false) // 新增 模态框显隐状态
let addRoleFormRef = ref() // ref获取表单子组件
let addRoleForm = reactive({ roleName: '', permissions: [], sort: 100 }) //校验前的数据
const addRoleFormRules = reactive({ // 校验规则
    roleName: [{ required: true, trigger: 'blur', message: '请输入至少4个字符', min: 4 }],
    permissions: [{ required: true, message: '请选择至少1个权限' }],
})
// ------------------------------------------------------------------------------------------新增------

// ------------------------------------------------------------------------------------------编辑------
let editBtnDialogVisible = ref(false) // 编辑 模态框显隐状态
let editAdminFormRef = ref() // ref获取表单子组件
let editAdminForm = reactive({ roleName: '', permissions: [], sort: 100 }) //校验前的数据
const editAdminFormRules = reactive({ // 校验规则
    roleName: [{ required: true, trigger: 'blur', message: '请输入至少4个字符', min: 4 }],
    permissions: [{ required: true, message: '请选择至少1个权限' }],
})
let formTreeRef = ref() // 权限树形结构ref
let permissionTreeDefault = [ // 树形结构数据
    // { id: 0, label: '首页' },
    // {
    //     id: 1, label: '管理员', children: [
    //         { id: 2, label: '管理员列表', children: [{ id: 4, label: '管理员新增' }, { id: 5, label: '管理员修改' }] },
    //         { id: 3, label: '角色管理', children: [{ id: 6, label: '角色新增' }, { id: 7, label: '角色修改' }] },
    //     ]
    // },
    // {
    //     id: 8, label: '商品管理', children: [
    //         { id: 9, label: '商品列表' },
    //         { id: 10, label: '商品新增' },
    //         { id: 11, label: '商品修改' },
    //         { id: 12, label: '商品删除' },
    //         { id: 13, label: '商品分类', children: [{ id: 14, label: '商品分类新增' }, { id: 15, label: '商品分类修改' }, { id: 16, label: '商品分类删除' }] },
    //     ]
    // },
    // { id: 17, label: '订单管理' },
    // { id: 18, label: '会员管理' },
]
let defaultCheckedKeys = ref([])
const promiseRes = proxy.$reqFuncAxios('post', '/api/admin/permissionList', { token: token }) // 请求权限列表
promiseRes.then(res => { getChildren(permissionTreeDefault, 0, res.data.data) }) // 扁平化数据转树
// ------------------------------------------------------------------------------------------编辑------

let searchInput = ref()

let tableData = ref([])
let tablePagination = ref({ pageSize: 12, count: 0 }) // 分页
let tableDataLoading = ref(true)

let currentPage = ref(1) // 分页激活项 默认第一页



loadTableData()

watch( //监听页码改变
    () => currentPage.value,
    (newVal, oleVal) => { loadTableData(newVal) },
)

function loadTableData(p, s) { // 加载角色列表
    tableDataLoading.value = true
    const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/roleLise', { page: p ? p + '' : '1', size: s ? s + '' : tablePagination.value.pageSize, token: token })
    promiseRes.then(res => {
        let resData = res.data.data
        tableData.value = resData.data || []
        tablePagination.value.total = resData.count
        tableDataLoading.value = false
    })
}
function roleOperate(o, e) { //o为操作类型 0新增1编辑2删除 e为当前条目 
    if (o === 0) { //新增
        console.log('新增');
        addBtnDialogVisible.value = true
        nextTick(() => { addRoleFormRef.value.resetFields(); }) // 点击的时候模态框可能没有加载完毕 需要nextTick后再ref出其中的方法
    }
    else if (o === 1) { //编辑
        console.log('编辑');
        editBtnDialogVisible.value = true
        let temp = []
        for (let i of e.permission) { temp.push(i.permission_id) }
        defaultCheckedKeys.value = temp
        editAdminForm.roleName = e.role_name
        editAdminForm.roleId = e.role_id
        editAdminForm.sort = e.sort
    } else if (o === 2) {
        console.log('删除', e);
    }
}
function formHandleClose(e) { // 模态框关闭
    formTreeRef.value.setCheckedKeys([], false) // 重置已选项
    addBtnDialogVisible.value = false
    editBtnDialogVisible.value = false
}
function formHandleCofirm(e) { // 新增或修改 表单校验 //提交 请求 e为未校验的表单数据
    if (e === 0) { //新增
        let query = { role_name: addRoleForm.roleName, permissions: formTreeRef.value.getCheckedKeys(), sort: addRoleForm.sort, token: token } // 单选时
        addRoleFormRef.value.validate((valid, fields) => { //ref获取表单子组件 valid为校验结果 fields为未通过验证的表单项
            if (valid) {
                const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/roleAddModify', query)
                promiseRes.then((res) => {
                    if (res.data.msg != "操作成功") { ElMessage.warning(`操作失败：${res.data.msg}`) }
                    else {
                        loadTableData(1) // 刷新列表
                        addRoleFormRef.value.resetFields() // 重置表单数据
                        addBtnDialogVisible.value = false; // 关闭模态框
                        ElMessage.success(`操作成功`); // 提示信息
                    }
                })
            } // 检验通过
            else { console.log('error', fields); } // 未通过 打印未通过的表单项
        })
    }
    else if (1) { // 编辑
        console.log(e);
        let query = { role_id: editAdminForm.roleId, role_name: editAdminForm.roleName, permissions: formTreeRef.value.getCheckedKeys(), sort: editAdminForm.sort, token: token }
        editAdminFormRef.value.validate((valid, fields) => {
            if (valid) {
                const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/roleAddModify', query)
                promiseRes.then((res) => {
                    if (res.data.msg != "操作成功") { ElMessage.warning(`操作失败：${res.data.msg}`) }
                    else {
                        console.log(res);
                        loadTableData(1) // 刷新列表
                        editAdminFormRef.value.resetFields() // 重置表单数据
                        editBtnDialogVisible.value = false; // 关闭模态框
                        ElMessage.success(`操作成功`); // 提示信息
                    }
                })
            }
            else { console.log('error', fields); } // 未通过 打印未通过的表单项
        })
    }
}
function findAdmin() { // 搜索
    console.log('findAdmin');
}
function getChildren(resTree, pid, originData) { //扁平化数据 转 树结构 // 结果数组 parent_id 扁平化数据 //https://juejin.cn/post/6987224048564437029#comment
    for (let i of originData) {
        if (i.parent_id === pid) {
            const newOne = { id: i.permission_id, label: i.permission_name, children: [], ...i }
            resTree.push(newOne)
            getChildren(newOne.children, newOne.permission_id, originData)
        }
    }
}

</script>
<style scoped>
.box {
    margin: 16px 20px;
    padding: 24px;
    background-color: #fff !important;
    display: block !important;
    /* overflow-x: auto; */
    min-width: fit-content;
}

.table-title {
    font-size: 16px;
    color: rgba(0, 0, 0, .75);
    margin-bottom: 16px;
}

.table-action-box {
    margin-bottom: 18px;
    display: flex;
    justify-content: space-between;

    line-height: 1.5;
    color: rgba(0, 0, 0, .65);
    transition: all .3s;
}

.table-actionBox-addBtn {
    border-radius: 2px;
    transition: all .3s;
}

.table-actionBox-addBtn-icon {
    margin-right: 5px;
    font-size: 20px;
}

.table-actionBox-searchInput {
    width: 300px;
}

.table-actionBox-searchInput-icon {
    cursor: pointer;
    transition: all .3s;
    font-size: 16px;
}

.table-actionBox-searchInput-icon:hover {
    color: #409EFF;
}

.dialog-box {
    margin: 0 100px;
}

/* .dialog-box :deep() .el-input__inner {
    text-align: left;
}

:deep().el-dialog__body {
    border-top: 1px solid #e8e8e8;
    border-bottom: 1px solid #e8e8e8;
    padding: 20px;
    box-sizing: border-box;
}

:deep().el-dialog__title {
    font-size: 16px;
}

:deep().el-dialog__header {
    padding: 16px 20px;
} */

.edit-btn {
    color: #1890ff;
    text-decoration: none;
    background-color: transparent;
    outline: none;
}

.edit-btn span {
    cursor: pointer;
    transition: color .3s;
    margin-right: 5px;
}

.edit-btn span:hover {
    color: #40a9ff;
}

.table-pagination {
    margin: 0 auto;
    width: fit-content;
    margin-top: 20px;
}
</style>